<?php


namespace App\Services\Game;


use App\DTOS\Admin\FunctionOpenDTO;
use App\DTOS\NeiGouDTO;
use App\Exceptions\ServiceException;
use App\Models\Game\Server;
use App\Utils\MyLog;
use Illuminate\Support\Facades\Http;


/** 内购
 * Class NeigouService
 * @package App\Services\Game
 */
class FunctionOpenService
{

    /**
     * @param NeiGouDTO $NeiGouDTO
     * @return bool
     * @throws ServiceException
     */
    public function pushToServer(FunctionOpenDTO $FunctionOpenDTO)
    {

        $row = Server::query()->where('can_push',1)->where("server_id",$FunctionOpenDTO->getServerId())->first();
        $pushUrl = data_get($row,'push_url');
        MyLog::info("传入的加赠比例是否".json_encode($FunctionOpenDTO->getServerId()));
        $requestBody = [
            [
            "Id"=>(int)$FunctionOpenDTO->getId(),
            "State"=>(int)$FunctionOpenDTO->getState(),
            "Name"=>$FunctionOpenDTO->getName(),
            "CloseType"=>(int)$FunctionOpenDTO->getCloseType(),
            'OpenLevel'=>(int)$FunctionOpenDTO->getOpenLevel(),
            'OpenType'=>(int)$FunctionOpenDTO->getOpenType() ?? 0,
            'OpenValue1'=>(int)$FunctionOpenDTO->getOpenValue1() ?? 0,
            'OpenValue2'=>(int)$FunctionOpenDTO->getOpenValue2() ?? 0,
            'isCloseCrossserver'=>(int)$FunctionOpenDTO->getIsCloseCrossserver() ?? 0,
            'IsCloseChiji'=>(int)$FunctionOpenDTO->getIsCloseChiji() ?? 0,
            'isCloseArena'=>(int)$FunctionOpenDTO->getIsCloseArena() ?? 0
            ]
            ];
        MyLog::info('推送消息体'.json_encode($requestBody));
        MyLog::info('推送地址'.json_encode($pushUrl));
        $response = Http::withHeaders(['Content-Type'=>'application/json'])
            ->post($pushUrl.'/Api/FunctionOpen',$requestBody);

        //Log::info("push to server response:" . $response);

        $body = json_decode($response->body(),true);
        $RetCode = data_get($body,'RetCode');
        MyLog::info('推送结果'.json_encode($body));
        if ($RetCode == 0){

            return true;
        }
        switch($RetCode) {
            case 1: throw new ServiceException("失败");
            case 3: throw new ServiceException("未找到角色");
            case 4: throw new ServiceException("操作正在处理");
            case 1000: throw new ServiceException("无效JSON参数");
            case 2000: throw new ServiceException("商品未找到");
        }
    }

}
